package com.woniu.util.handler;

import com.alibaba.fastjson.JSON;
import com.woniu.util.utils.HttpResult;
import com.woniu.util.utils.JWTUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功处理器
 */
@Component
public class LoginSucessHandler implements AuthenticationSuccessHandler {

    @Autowired(required = false)
    private StringRedisTemplate stringRedisTemplate;

    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        User user= (User) authentication.getPrincipal();
        Map map = new HashMap();
        map.put("username", user.getUsername());
        String jwt = JWTUtil.createJWT(map);
        //1.把jwt放到redis 2.以参数形式把jwt传到前端
        stringRedisTemplate.opsForValue().set("jwt:"+user.getUsername(),jwt,30, TimeUnit.MINUTES);


        httpServletResponse.getWriter().write(JSON.toJSONString( new HttpResult().ok(jwt)));


    }
}
